// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: qiang

#include "coin2/exchange/bitget_base/api_util/auth_key.h"

#include <boost/algorithm/string/replace.hpp>

#include "coin2/base/time.h"
#include "coin2/exchange/base/api_util/api_signature.h"
#include "coin2/exchange/base/api_util/json_writer.h"

std::string BitgetBaseAuth::GetCurrTimeSeconds() {
  return std::to_string(GetCurrentTimestamp() / 1000000);
}

std::string BitgetBaseAuth::GetSignature(
    const std::string& secret_key,
    const std::string& address,
    const std::string& method,
    const std::string& timestamp,
    const std::string& param) {
  if (secret_key.empty()) {
    throw std::runtime_error("[Bitget] secret key is empty");
  }
  std::string cre = timestamp + method + address + param;
  return ApiSignatureUtil::GetSignatureByHmacSHA256(cre, secret_key);
}

std::string BitgetWsAuth::CreateSignature() const {
  std::string args;
  std::string ts_str = std::to_string(GetCurrentTimestamp() / 1000000000);
  std::string signa =
      ApiSignatureUtil::GetSignatureByHmacSHA256(ts_str + "GET/user/verify", key_.secret_key());
    args = fmt::format(
        R"({{"apiKey": "{}", "passphrase": "{}", "timestamp": "{}", "sign": "{}"}})",
        key_.access_key(),
        key_.GetValue("passphrase").value(),
        ts_str,
        signa);

  return fmt::format(R"({{"op": "login", "args": [{}]}})", args);
}

std::vector<std::pair<std::string, std::string>> BitgetRestAuth::GetHeaderSet(
    const std::string& address,
    const std::string& method,
    const std::string& param) const {
  std::vector<std::pair<std::string, std::string>> out;
  std::string ts_str = GetCurrTimeSeconds();
  std::string signa = GetSignature(key_.secret_key(), address, method, ts_str, param);
  out.push_back(std::make_pair("ACCESS-KEY", key_.access_key()));
  out.push_back(std::make_pair("ACCESS-SIGN", signa));
  out.push_back(std::make_pair("ACCESS-TIMESTAMP", ts_str));
  out.push_back(std::make_pair("ACCESS-PASSPHRASE", key_.GetValue("passphrase").value()));
  out.push_back(std::make_pair("Content-Type", "application/json"));
  out.push_back(std::make_pair("locale", "en-US"));
  return out;
}

AsioHttpContext* BitgetRestAuth::CreateRequestByGetWithSignature(
    const std::string& address,
    UrlParamsBuilder* builder) {
  std::string query_string = builder->ComputeQueryString();
  CHECK_THROW(builder->ComputePostBody().empty()) << "It is GET Method, No Payload";
  std::string target = address;
  if (!query_string.empty()) {
    target += "?" + query_string;
  }
  return AsioHttpContext::NewGet(host_, port_, bind_ip_, target, GetHeaderSet(target, "GET", ""));
}

AsioHttpContext* BitgetRestAuth::CreateRequestByPostWithSignature(
    const std::string& address,
    UrlParamsBuilder* builder) {
  std::string query_string = builder->ComputeQueryString();
  std::string post_body = builder->ComputePostBody();
  std::string target = address;
  if (!query_string.empty()) {
    target += "?" + query_string;
  }

  return AsioHttpContext::NewPost(
      host_,
      port_,
      bind_ip_,
      target,
      GetHeaderSet(target, "POST", post_body),
      post_body);
}

AsioHttpContext* BitgetRestAuth::CreateRequestByDeleteWithSignature(
    const std::string& address,
    UrlParamsBuilder* builder) {
  std::string query_string = builder->ComputeQueryString();
  std::string post_body = builder->ComputePostBody();
  std::string target = address;
  if (!query_string.empty()) {
    target += "?" + query_string;
  }
  return AsioHttpContext::NewDelete(
      host_,
      port_,
      bind_ip_,
      target,
      GetHeaderSet(target, "DELETE", post_body),
      post_body);
}